package com.zhongxiangspace.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhongxiangspace.entity.ArticleType;
import com.zhongxiangspace.entity.QueryAnalyzer;
import com.zhongxiangspace.result.ExceptionResult;
import com.zhongxiangspace.result.PageResult;
import com.zhongxiangspace.result.Result;
import com.zhongxiangspace.service.AdvertService;
import com.zhongxiangspace.service.ArticleService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class NewsListController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private AdvertService advertService;

    @GetMapping({"lists/news"})
    public String news(Model model) {
        List<ArticleType> articleTypeList = this.articleService.queryType(Integer.valueOf(1));
        return news(model, ((ArticleType) articleTypeList.get(0)).getId(), Integer.valueOf(1));
    }

    @GetMapping({"lists/news{id}/pv{page}"})
    public String news(Model model, @PathVariable("id") Integer id, @PathVariable("page") Integer page) {
        Map<String, Object> map = new HashMap();
        List<ArticleType> articleTypeList = this.articleService.queryType(Integer.valueOf(1));
        map.put("articleTypeList", articleTypeList);
        if (id == null) {
            id = ((ArticleType) articleTypeList.get(0)).getId();
        }
        QueryAnalyzer advertQueryAnalyzer = new QueryAnalyzer();
        advertQueryAnalyzer.setShowCode(Integer.valueOf(1));
        List<Map<String, Object>> advertList = this.advertService.queryAdvert(advertQueryAnalyzer);
        model.addAttribute("advertList", advertList);

        model.addAttribute("type_id", id);
        model.addAttribute("data", map);
        return "list/news_list_mobile";
    }

    @ResponseBody
    @PostMapping({"/lists/ajaxNewsData"})
    public Result ajxaData(QueryAnalyzer queryAnalyzer) {
        try {
            queryAnalyzer.setShowCode(Integer.valueOf(1));
            PageHelper.startPage(queryAnalyzer.getPage().intValue(), 16, "articles.modify_time  DESC");
            Page<Map<String, Object>> articlesList = (Page) this.articleService.articlesAll(queryAnalyzer);
            return new PageResult(articlesList.getPageNum(), articlesList.getPageSize(), articlesList.getTotal(), articlesList.getPages(), articlesList.getResult(), true);
        } catch (Exception e) {
            e.printStackTrace();
            return new ExceptionResult(e);
        }
    }
}
